package br.com.skolar.client.framework;

import com.google.gwt.event.dom.client.DomEvent;
import com.google.gwt.user.client.ui.CellPanel;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.PushButton;

public class ButtonPanel extends Composite {
	private HorizontalPanel buttonsPanel;
	private PushButton cancelButton, saveButton;
	private boolean cancelButtonBound, saveButtonBound;

	public ButtonPanel(String save) {
		saveButton = new PushButton(save);
		buttonsPanel = new HorizontalPanel();
		buttonsPanel.add(saveButton);
		initWidget(buttonsPanel);
	}

	public ButtonPanel(String cancel, String save) {
		cancelButton = new PushButton(cancel);
		saveButton = new PushButton(save);
		buttonsPanel = new HorizontalPanel();
		buttonsPanel.add(cancelButton);
		buttonsPanel.add(saveButton);
		initWidget(buttonsPanel);
	}

	public ButtonPanel setCancelHandler(ButtonHandler cancelHandler) {
		cancelButtonBound = true;
		cancelButton.addKeyUpHandler(cancelHandler);
		cancelButton.addClickHandler(cancelHandler);
		return this;
	}

	public ButtonPanel setSaveHandler(final ButtonHandler saveHandler) {
		saveButtonBound = true;
		ButtonHandler h = new ButtonHandler() {
			@Override
			protected void onEvent(DomEvent e) {
				enableButtons(false);
				saveHandler.onEvent(e);
			}
		};
		saveButton.addKeyUpHandler(h);
		saveButton.addClickHandler(h);
		return this;
	}

	public void enableButtons(boolean enabled) {
		if (cancelButton!=null)
			cancelButton.setEnabled(enabled);
		saveButton.setEnabled(enabled);
	}

	@Override
	protected void onAttach() {
		super.onAttach();
		buttonsPanel.setStyleName("borderless");
		if (cancelButton!=null && !cancelButtonBound)
			throw new Error("Cancel Button not bound");
		if (!saveButtonBound)
			throw new Error("Save Button not bound");
		try {
			CellPanel parent = ((CellPanel) getParent());
			parent.setStyleName("borderless");
			parent.setCellHorizontalAlignment(this, HasHorizontalAlignment.ALIGN_RIGHT);
		} catch (Exception e) {
		}
	}
}